/** @format */

import { resultsModel } from '../../../sdk'
import { CODE_TYPES } from '../../../errorCode'
import { dbFindOne } from '../../common/mongodb'
import { USER_DB_NAME } from '../../../db'
import { getTask, getTodayCompleteGrowTask, getTodayCompleteTask, getTotalCompleteTask } from '../task'
import { TASK_RATE_TYPE } from '../../../constants'

/**
 *  检查inviteId是否合法 返回邀请人的用户信息
 *
 * @export
 * @param {IContext<{ activityId: string; inviteId: string }>} context
 * @return {*}
 */
export default async function checkGrowInviteId(
  context: IContext<{ activityId: string; inviteId: string; key: string }>,
  { activityInfo }: IControllerInfos
) {
  const {
    openId,
    data: { activityId, inviteId, key }
  } = context
  if (key === 'invite') {
    //如果类型为邀请
    if (!inviteId) {
      //如果邀请id不为空
      // 自己邀请自己
      if (openId === inviteId) return resultsModel.error(CODE_TYPES.ERROR_NO_INVITE_SELF)

      // 获取邀请者信息
      const inviteUserInfo = await dbFindOne<IUserInfo>(context, USER_DB_NAME, {
        activityId,
        openId: inviteId
      })

      // inviteId的用户信息查询不到, 则inviteId无效
      if (!inviteUserInfo) return resultsModel.error(CODE_TYPES.ERROR_INVALID_INVITE_ID)

      const {
        tasks: { invite }
      } = activityInfo

      const { rateType, times } = invite

      // 助力次数超限制
      if (rateType === TASK_RATE_TYPE.EVERYDAY) {
        const task = await getTask(context, inviteUserInfo.openId)
        // 每日任务今天已经完成
        const { todayCompleteTimes, todayTaskInfo } = getTodayCompleteGrowTask(key, task)
        if (todayCompleteTimes >= times) {
          return resultsModel.error(CODE_TYPES.ERROR_INVITE_TIMES_LIMIT)
        }
      }
      if (rateType === TASK_RATE_TYPE.FOREVER) {
        // 永久邀请任务超出次数
        const { completeTimes } = getTotalCompleteTask(key, inviteUserInfo)
        if (completeTimes >= times) {
          return resultsModel.error(CODE_TYPES.ERROR_INVITE_TIMES_LIMIT)
        }
      }

      return {
        inviteUserInfo
      }
    } else {
      return resultsModel.error(CODE_TYPES.ERROR_INVALID_INVITE_ID)
    }
  }
}
